package com.novellotus.iov.carvice.activity;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jakewharton.rxbinding2.view.RxView;
import com.novellotus.iov.carvice.R;
import com.novellotus.iov.carvice.bean.MqttListCarBean;
import com.novellotus.iov.carvice.bean.MqttSingleCarStatue;
import com.novellotus.iov.carvice.bean.MqttVehicleBean;
import com.novellotus.iov.carvice.fragment.BaseCarFragment;
import com.novellotus.iov.carvice.fragment.CarStatuesFragment;
import com.novellotus.iov.carvice.model.MqttModule;
import com.novellotus.iov.carvice.retrofit.BaseEntity;
import com.novellotus.iov.carvice.retrofit.BaseObserver;
import com.novellotus.iov.carvice.retrofit.RetrofitFactory;
import com.novellotus.iov.carvice.retrofit.RxSchedulers;
import com.novellotus.iov.carvice.utils.MyUtils;
import com.novellotus.iov.carvice.utils.SharedPreferencesUtils;
import com.novellotus.iov.carvice.view.TipsDialog;
import com.tbruyelle.rxpermissions2.Permission;

import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.functions.Consumer;

/**
 * 车辆详情页面
 */
public class CarDetailActivity extends CarBaseActivity implements TipsDialog.ClickTipsInterface, MqttModule.MqttMessageInterface, BaseCarFragment.CarFragmentInterface {

    @BindView(R.id.tv_tittle)
    TextView tv_tittle;
    @BindView(R.id.content)
    FrameLayout content;
    @BindView(R.id.tabLayout)
    LinearLayout tabLayout;
    @BindView(R.id.rlt_navigation)
    RelativeLayout rlt_navigation;
    @BindView(R.id.tv_loading)
    TextView tv_loading;
    private String vin = "";
    private String plate = "";
    private CarStatuesFragment carStatuesFragment;
    private TipsDialog tipsDialog;
    private MqttModule mqttModule;
    private boolean isCancel;
    String[] key;

    @Override
    void initContentView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_car_detail);

    }


    @Override
    void init() {
        // StatusBarUtil.setTranslucent(this);
        tipsDialog = new TipsDialog(this);
        vin = getIntent().getExtras().getString("vin");
        plate = MyUtils.getPlateString(getIntent().getExtras().getString("plate"));
        key = SharedPreferencesUtils.getKey(this);
        initMqtt();
        setNavigation();
        tv_tittle.setText(plate);
        setContent();
    }


    void initMqtt() {
        mqttModule = new MqttModule(this, this, key[0], key[1]);
        String[] topic = new String[]{"$NL/ne/evbus/" + key[2] + "/follow_vehicles/" + vin, "$NL/ne/evbus/" + key[2] + "/real_time_info/" + vin};
        mqttModule.setTop(topic, 2);
        mqttModule.startReconnect();
    }

    void setContent() {
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        carStatuesFragment = CarStatuesFragment.newInstance(plate, vin);
        carStatuesFragment.setInterface(this);
        fragmentTransaction.replace(R.id.content, carStatuesFragment);
        fragmentTransaction.commit();
    }


    /**
     * 导航之前先检查权限
     */

    void setNavigation() {
        RxView.clicks(rlt_navigation)
                .compose(RxSchedulers.lifecycle(this)).throttleFirst(1, TimeUnit.SECONDS)
                .compose(rxPermissions.ensureEach(Manifest.permission.ACCESS_FINE_LOCATION))
                .subscribe(new Consumer<Permission>() {
                    @Override
                    public void accept(Permission permission) throws Exception {
                        if (permission.granted) {
                            openActivity(MapChargeStationActivity.class);
                        } else {
                            MyUtils.showToast(CarDetailActivity.this, "定位权限已经被禁止，请到设置中允许相关权限");
                        }
                    }
                });
    }

    @OnClick(R.id.img_back)
    void back() {
        finish();
    }

    /**
     * 确定取消关注车辆
     */
    @Override
    public void clickTipsButton() {
        if (isCancel) {

            Observable<BaseEntity<Boolean>> observable = RetrofitFactory.getInstance().cancelFollowVehicle(vin, SharedPreferencesUtils.getKey(this)[0]);
            observable.compose(RxSchedulers.<BaseEntity<Boolean>>compose())
                    .subscribe(new BaseObserver<Boolean>(this) {
                        @Override
                        public void onSuccess(Boolean response) {
                            MyUtils.showToast(CarDetailActivity.this, "取消关注成功!");
                            Intent intent = new Intent(CarDetailActivity.this, MainActivityOld.class);
                            intent.putExtra("isUpdate", true);
                            setResult(101, intent);
                            finish();
                        }

                        @Override
                        public void onFail(int code, String msg) {
                            MyUtils.showToast(CarDetailActivity.this, msg);
                        }

                        @Override
                        public void onError(String msg) {

                        }
                    });
        }

        tipsDialog.dismiss();
    }

//    @OnClick(R.id.rlt_navigation)
//    void openNavigation() {
//        openActivity(NavigationActivity.class);
//    }

    @OnClick(R.id.rlt_cancel)
    void cancel() {
        isCancel = true;
        tipsDialog.initDialog("取消关注", "取消关注本车后将无法查看该辆车数据，确定取消关注本车吗?", this);
        tipsDialog.show();
    }

    /**
     * 报修
     */
    @OnClick(R.id.rlt_add_service)
    void addService() {
        Bundle bundle = new Bundle();
        bundle.putString("plate", plate.replace(" ", ""));
        openActivity(AddFailureActivity.class, bundle);
    }


//    public void getData() {
//
//        Observable<BaseEntity<RxCarData>> observable = RetrofitFactory.getInstance().getVehicleData(vin, SharedPreferencesUtils.getKey(this)[0]);
//        observable.compose(RxSchedulers.<BaseEntity<RxCarData>>compose())
//                .subscribe(new BaseObserver<RxCarData>(this) {
//                    @Override
//                    public void onSuccess(RxCarData response) {
//
//                        content.setVisibility(View.VISIBLE);
//                        tabLayout.setVisibility(View.VISIBLE);
//                        carStatuesFragment.setData(response);
//                    }
//
//                    @Override
//                    public void onFail(int code, String msg) {
//
//                        content.setVisibility(View.INVISIBLE);
//                        tabLayout.setVisibility(View.INVISIBLE);
//                    }
//
//                    @Override
//                    public void onError(String msg) {
//                        content.setVisibility(View.INVISIBLE);
//                        tabLayout.setVisibility(View.INVISIBLE);
//
//                    }
//                });
//    }


//    @Override
//    public void onReload() {
//        getData();
//    }

    MqttVehicleBean mqttVehicleBean;
    long mqttVehicleBeanTime;

    @Override
    public void getTopic(MqttListCarBean mqttListCarBean, MqttVehicleBean mqttVehicleBean, String vin) {
        this.mqttVehicleBean = mqttVehicleBean;
        mqttVehicleBeanTime = System.currentTimeMillis();
        //如果收到的单车数据比车辆状态主题晚，而且相差的时间在2秒内，则在这里刷新
        if (0 <= mqttVehicleBeanTime - mqttSingleCarStatueTime && mqttVehicleBeanTime - mqttSingleCarStatueTime < 10000) {
            if (mqttSingleCarStatue != null) {
                int carType = MyUtils.carType(mqttSingleCarStatue.getOnlineStatus(), mqttSingleCarStatue.getChargeStatus(), mqttSingleCarStatue.getAlarmStatus());
                int carDetailType = MyUtils.carDetailType(mqttSingleCarStatue.getOnlineStatus(), mqttSingleCarStatue.getChargeStatus(), mqttSingleCarStatue.getAlarmStatus());
                carStatuesFragment.mqttUpdate(mqttVehicleBean, carType, carDetailType);
            }
        }
    }

    MqttSingleCarStatue mqttSingleCarStatue;
    long mqttSingleCarStatueTime;

    @Override
    public void getSingleCarStatue(MqttSingleCarStatue mqttSingleCarStatue) {
        this.mqttSingleCarStatue = mqttSingleCarStatue;
        mqttSingleCarStatueTime = System.currentTimeMillis();
        //如果收到的车辆状态比单车数据主题早，而且相差的时间在2秒内，则在这里刷新
        if (0 <= mqttSingleCarStatueTime - mqttVehicleBeanTime && mqttSingleCarStatueTime - mqttVehicleBeanTime < 10000) {
            int carType = MyUtils.carType(mqttSingleCarStatue.getOnlineStatus(), mqttSingleCarStatue.getChargeStatus(), mqttSingleCarStatue.getAlarmStatus());
            int carDetailType = MyUtils.carDetailType(mqttSingleCarStatue.getOnlineStatus(), mqttSingleCarStatue.getChargeStatus(), mqttSingleCarStatue.getAlarmStatus());
            if (mqttVehicleBean != null) {
                carStatuesFragment.mqttUpdate(mqttVehicleBean, carType, carDetailType);
            }
        } else if (mqttSingleCarStatue != null) {
            int carType = MyUtils.carType(mqttSingleCarStatue.getOnlineStatus(), mqttSingleCarStatue.getChargeStatus(), mqttSingleCarStatue.getAlarmStatus());
            if (carType == 0 && mqttVehicleBean != null) {

                carStatuesFragment.mqttUpdate(mqttVehicleBean, 0, 0);
            }
        }
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        if (mqttModule != null) {
            mqttModule.startReconnect();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mqttModule != null) {
            mqttModule.stopConnect();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mqttModule != null) {
            mqttModule.destroyModule();
        }
        carStatuesFragment = null;
        tipsDialog = null;
        mqttModule = null;
    }


    @Override
    public void loadStatue(int statue) {
        tv_loading.setVisibility(View.GONE);
        if (statue == 1) {
            content.setVisibility(View.VISIBLE);
            tabLayout.setVisibility(View.VISIBLE);
        } else {
            content.setVisibility(View.VISIBLE);
            tabLayout.setVisibility(View.INVISIBLE);
        }
    }
}
